const LogModel = require('../../model/Log');
const moment = require('moment');
const ObjectID = require('mongodb').ObjectID;
const ExpenseHistory = require('../../model/ExpenseHistory')
const PointHistory = require('../../model/PointHistory')
const Member = require('../../model/Member')
const User = require('../../model/User')
const Order = require('../../model/Order')
const ProductSub = require('../../model/ProductSub')
const Voucher = require('../../model/Voucher')
const Reimburse = require('../../model/Reimburse')
const Staff = require('../../model/Staff')
const AdminUser = require('../../model/AdminUser')

module.exports = {


    exportExpenseHistory: async(req, res, next) => {
        try {
            if (req.body.startDate) {
                var startDate = new Date(req.body.startDate)
            }
            if (req.body.endDate) {
                var endDate = new Date(req.body.endDate)
            }
            let option = {}
            option.isDelete = 0
            if(req.body.billNumber){
                option.billNumber = new RegExp(req.body.billNumber)
            }
            if (req.body.id) {
                option.store = req.body.id
            }
            // if (req.body.memberNo) {
            //     let member = await Member.findOne({ code: req.body.memberNo, isDelete: 0 }, '_id').exec()
            //     option.member = member._id
            // }
            if (req.body.memberNo) {
                let member = (await Member.find({ code: new RegExp(req.body.memberNo), isDelete: 0 }, '_id').exec()).map(e=>{return e._id})
                option.member = {$in:member}
            }
            if (req.body.cellphone) {
                option.cellphone = req.body.cellphone
            }
            if (startDate && !endDate) {
                option.createdAt = { $gte: startDate }
            } else if (!startDate && endDate) {
                option.createdAt = { $lte: endDate }
            } else if (startDate && endDate) {
                option.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            }
            if (req.session.user.store.length !== 0) {
                let storeId = []
                req.session.user.store.forEach(e => {
                    storeId.push({ store: ObjectID(e) })
                })
                option.$or = storeId
            }
            let expenseHistory = await ExpenseHistory.find(option).populate('order store member staff account').sort({ createdAt: -1 }).exec()
            let data = []
            // data.push(['会员号', '手机号', '日期', '消费门店', '消费金额', '赠送积分', '审核状态', '使用积分', '积分余额'])
            data.push(['会员号', '手机号', '创建日期','复核日期','审核日期', '消费门店', '账单号','消费金额','待审核积分','使用积分','积分余额','复核状态','审核状态','处理员工'])
            expenseHistory.forEach(e => {
                let verifyText = "未知"
                if(e.verify === 1){
                    verifyText = "审核通过"
                }else if(e.verify ===2){
                    verifyText = "审核未通过"
                }else if(e.verify === 0 ){
                    verifyText = "未审核"
                }
                let reviewText = "未知"
                if(e.review === 1){
                    reviewText = "复核通过"
                }else if(e.review ===2){
                    reviewText = "复核未通过"
                }else if(e.review === 0 ){
                    reviewText = "未复核"
                }
                let accountText = "未知"
                if(e.staff != undefined){
                    accountText = "手机号："+e.staff.cellphone
                }
                if(e.account !=undefined){
                    accountText = "PC账号："+e.account.account
                }
                data.push([e.member == null?'未知':e.member.code, e.cellphone, moment(e.createdAt).format('YYYY-M-D H:mm:ss'),moment(e.reviewAt).format('YYYY-M-D H:mm:ss'),moment(e.verifyAt).format('YYYY-M-D H:mm:ss'), e.store == null?'未知':e.store.name,e.billNumber, e.amount, e.earnPoints, e.point, e.member == null?'未知':e.member.point,reviewText,verifyText,accountText])
            })
            return res.ok('获取消费记录成功', data)
        } catch (e) {
            next(e)
        }
    },

    exportMemberPoint: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.order) {
                option.order = req.body.order
            }
            if (req.body.manual) {
                option.manual = req.body.manual
            }
            if (req.body.amount) {
                option.amount = req.body.amount
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            let pointHistory = await PointHistory.find(option).populate('member order').populate({
                path: 'expenseHistory',
                select: 'store',
                populate: { path: 'store', select: 'name' }
            }).exec()
            let data = []
            data.push(['会员号', '积分余额', '到期积分', '有效积分', '门店'])
            pointHistory.forEach(e => {
                data.push([e.member == null?'未知':e.member.code, e.member == null?'未知':e.member.point, 0, e.amount, e.expenseHistory.store.name])
            })
            return res.ok('获取积分记录成功', data)
        } catch (e) {
            next(e)
        }
    },

    exportMimiappUser: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.cellphone) {
                option.cellphone = new RegExp(req.body.cellphone)
            }
            if (req.body.name) {
                option.nickName = new RegExp(req.body.name, 'i')
            }
            if (req.body.startDate) {
                option.createdAt = { $gte: new Date(req.body.startDate) }
            }
            if (req.body.endDate) {
                option.createdAt = { $lte: new Date(req.body.endDate) }
            }
            if (req.body.startDate && req.body.endDate) {
                option.createdAt = { $gte: new Date(req.body.startDate), $lte: new Date(req.body.endDate) }
            }
            let user = await User.aggregate([
                {
                  $match: option
                },
                {
                $lookup:{
                    from:"member",
                    localField:'openid',
                    foreignField:'openid',
                    as:'member'
                },
            }]).exec()
            let data = []
            data.push(['昵称', '性别', '手机号', '会员等级', '会员积分','到期积分','创建日期','赠送的积分'])
            user.forEach(async e => {
                // let givePoint = 0
                // if(e.pointHistory.length !=0){
                //     if(e.pointHistory[0].amount == 100&&(!e.pointHistory[0].expenseHistory)&&e.pointHistory[0].type ==0&&new Date(e.pointHistory[0].expenseDate)>=new Date('2020-08-24')){
                //         givePoint =e.pointHistory[0].amount
                //     } 
                // }
                data.push([e.nickName, e.gender==1?'男':e.gender==2?'女':'未知', e.cellphone, e.member.length==0?'未知':e.member[0].type, e.member.length==0?0:e.member[0].point,0,moment(e.createdAt).format('YYYY-M-D'),e.member.length==0?0:e.member[0].newUserGivePoint])
})
            return res.ok('获取小程序用户成功', data)
        } catch (e) {
            next(e)
        }
    },

    exportStoreExpenseHistory: async(req, res, next) => {
        try {
            if (req.body.startDate) {
                var startDate = new Date(req.body.startDate)
            }
            if (req.body.endDate) {
                var endDate = new Date(req.body.endDate)
            }
            let option = {}
            option.isDelete = 0
            if (req.body.id) {
                option.store = ObjectID(req.body.id)
            }
            if (req.body.memberNo) {
                let member = await Member.findOne({ code: req.body.memberNo, isDelete: 0 }, '_id').exec()
                option.member = ObjectID(member._id)
            }
            if (req.body.cellphone) {
                option.cellphone = req.body.cellphone
            }
            if (startDate && !endDate) {
                option.createdAt = { $gte: startDate }
            } else if (!startDate && endDate) {
                option.createdAt = { $lte: endDate }
            } else if (startDate && endDate) {
                option.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            }
            // let expenseHistory = await ExpenseHistory.find(option).populate('order store member').sort({ createdAt: -1 }).exec()
            let expenseHistory = await ExpenseHistory.aggregate([
                {
                  $match: option
                },
                {
                  $sort:{
                    createdAt: -1
                  }
                },
                {
                    $lookup:{
                        from:"userPoint",
                        localField:'openid',
                        foreignField:'openid',
                        as:'userPoint'
                    }
                },
                {
                    $lookup:{
                        from:"store",
                        localField:'store',
                        foreignField:'_id',
                        as:'store'
                    },
                },
                {
                    $lookup:{
                        from:"member",
                        localField:'member',
                        foreignField:'_id',
                        as:'member'
                    }
                },
                {
                    $lookup:{
                        from:"order",
                        localField:'order',
                        foreignField:'_id',
                        as:'order'
                    }
                }
        ]).exec()
            let data = []
            data.push(['会员号', '手机号', '日期', '消费门店', '消费金额', '赠送积分', '使用积分', '积分余额','过期积分'])
            expenseHistory.forEach(e => {
                data.push([e.member.length == 0?'未知':e.member[0].code, e.cellphone, moment(e.createdAt).format('YYYY-M-D H:mm:ss'), e.store.length == 0?'未知':e.store[0].name, e.amount, e.earnPoints, e.point, e.member.length == 0?'未知':e.member[0].point,(e.userPoint.length == 0||e.userPoint[0].expiredPoint==null)?'未知':e.userPoint[0].expiredPoint])
            })
            return res.ok('获取消费记录成功', data)
        } catch (e) {
            next(e)
        }
    },

    
    exportVoucherOrder: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            option.type = 1
            if (req.body.id) {
                option._id = req.body.id
            }
            if (req.body.name) {
                let user = await User.find({ nickName: new RegExp(req.body.name, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            if (req.body.status) {
                option.status = req.body.status
            }


            let orderLIst = await Order.find(option).sort({ createdAt: -1 }).populate('userVoucher user').populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).populate({
                path: 'staff',
                model: Staff,
                populate: { path: 'store' }
            }).populate({
                path: 'account',
                model: AdminUser,
                populate: { path: 'store' }
            }).exec()
            let tempData = []
            orderLIst.forEach(async e => {
                let temp = JSON.parse(JSON.stringify(e))
                temp.cellphone = e.user.cellphone
                temp.userVoucher = e.userVoucher[0]
                tempData.push(temp)
            })
            let data = []
            data.push(['订单ID', '订单状态', '兑换券名字', '兑换券数量', '手机号', '积分总价', '核销状态', '核销时间','创建时间','核销员工','核销员工所在门店'])
            tempData.forEach(e => {
                data.push([e._id,e.status == 0 ? '待付款': e.status == 1 ? '已付款' : e.status == 2 ? '退款' : e.status == 3 ? '退款中' : e.status == 4 ? '已发货' : '已退款' ,e.products[0].voucher.title,e.products[0].amount, e.cellphone,e.totalPoint,e.userVoucher && e.userVoucher.status == 0 ? '未使用' : '已使用', moment(e.useDate).format('YYYY-M-D H:mm:ss'),moment(e.createdAt).format('YYYY-M-D H:mm:ss'),e.staff != null ? e.staff.cellphone:'',e.staff != null ? e.staff.store[0].name:''])
            })
            return res.ok('获取兑换券订单成功', data)
        } catch (e) {
            next(e)
        }
    },
    
    exportProductOrder: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            option.type = 0
            if (req.body.id) {
                option._id = req.body.id
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.name) {
                let user = await User.find({ nickName: new RegExp(req.body.name, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.cellphone) {
                let user = await User.find({ cellphone: new RegExp(req.body.cellphone, 'i') }, 'openid').exec()
                let openid = user.map(value => {
                    return value.openid
                })
                option.openid = openid
            }
            if (req.body.type) {
                option.type = req.body.type
            }
            if (req.body.status) {
                option.status = req.body.status
            }
            let orderList = await Order.find(option).sort({ createdAt: -1 }).populate('user', 'cellphone').populate({
                path: 'products.product',
                model: ProductSub,
                populate: { path: 'product' }
            }).populate({
                path: 'products.voucher',
                model: Voucher
            }).populate({
                path: 'reimburse',
                model: Reimburse
            }).exec()
            let tempData = []
            orderList.forEach(async e => {
                let temp = JSON.parse(JSON.stringify(e))
                temp.cellphone = e.user.cellphone
                tempData.push(temp)
            })
            let data = []
            data.push(['订单ID', '订单状态', '积分总价', '手机号', '发货时间', '创建时间'])
            tempData.forEach(e => {
                data.push([e._id,e.status == 0 ? '待付款': e.status == 1 ? '已付款' : e.status == 2 ? '退款' : e.status == 3 ? '退款中' : e.status == 4 ? '已发货' :  '已退款',e.totalPoint, e.cellphone, moment(e.shipDate).format('YYYY-M-D H:mm:ss'),moment(e.createdAt).format('YYYY-M-D H:mm:ss')])
            })
            return res.ok('获取商品订单成功', data)
        } catch (e) {
            next(e)
        }
    },

    exportStorePointList: async (req, res, next) => {
        try {
            let startDate = new Date(moment().subtract(1, 'months').startOf('month'))
            let endDate = new Date(moment().subtract(1, 'months').endOf('month'))
            if(req.body.month){
                startDate = new Date(moment(req.body.month).startOf('month'))
                endDate = new Date(moment(req.body.month).endOf('month'))
            }
            let option = {}
            option.isDelete = 0
            option.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            let expenseHistory = await ExpenseHistory.aggregate([
                {
                  $match: option
                },
                {
                    $group:{_id:"$store",giftPoint:{$sum:"$earnPoints"},usedPoint:{$sum:"$point"}}
                },
                {
                    $lookup:{
                        from:"store",
                        localField:'_id',
                        foreignField:'_id',
                        as:'store'
                    },
                },
                {
                    $sort: {
                        _id: -1
                    }
                }
                ]).exec()
                let data = []
                data.push(['门店', '已审核积分', '已使用积分', '兑换券使用积分'])
                for(let j=0;j<expenseHistory.length;j++){
                    expenseHistory[j].store = expenseHistory[j].store[0].name
                    let tempPoint = 0 
                    let storeId = expenseHistory[j]._id
                    let voucherOrderOption = {}
                    voucherOrderOption.isDelete = 0
                    voucherOrderOption.type = 1
                    voucherOrderOption.status = 1
                    voucherOrderOption.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
                    voucherOrderOption.store = {$in:storeId}
                    let voucherOrder = await Order.find(voucherOrderOption).exec()
                    voucherOrder.forEach(i =>{
                        tempPoint = tempPoint + i.totalPoint
                    })
                    expenseHistory[j].voucherOrderPoint = tempPoint
                    data.push([expenseHistory[j].store,expenseHistory[j].giftPoint,expenseHistory[j].usedPoint,expenseHistory[j].voucherOrderPoint])
                    console.log(data)
                }



                // await expenseHistory.forEach(async e => {
                //     e.store = e.store[0].name
                //     let tempPoint = 0 
                //     let storeId = e._id
                //     let voucherOrderOption = {}
                //     // voucherOrderOption.isDelete = 0
                //     // voucherOrderOption.type = 1
                //     // voucherOrderOption.status = 1
                //     // voucherOrderOption.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
                //     voucherOrderOption.store = {$in:storeId}
                //     let voucherOrder = await Order.find(voucherOrderOption).exec()
                //     voucherOrder.forEach(i =>{
                //         // console.log(e.store,i.totalPoint)
                //         tempPoint = tempPoint + i.totalPoint
                //     })
                //     e.voucherOrderPoint = tempPoint
                //     data.push([e.store,e.giftPoint,e.usedPoint,e.voucherOrderPoint])
                //     console.log(data)
                // });
            // let productPoint = 0
            // let voucherPoint = 0
            // let orderOption = {}
            // orderOption.isDelete = 0
            // // orderOption.status = 1
            // orderOption.$or = [{ status: 1}, { status: 4}]
            // orderOption.$and = [{ createdAt: { $gte: startDate } }, { createdAt: { $lte: endDate } }]
            // let orderList = await Order.find(orderOption).exec()
            // orderList.forEach(e =>{
            //         if(e.type == 0){
            //             productPoint = productPoint + e.totalPoint
            //         }else if(e.type == 1){
            //             voucherPoint = voucherPoint + e.totalPoint
            //         }
            //     })
            // let manualChangePoint = 0
            // let manualChangePointOption = {}
            // manualChangePointOption.isDelete=0
            // manualChangePointOption.$and = [{ expenseDate: { $gte: startDate } }, { expenseDate: { $lte: endDate } }]
            // let manualChangePointList = await ManualChangePoint.find(manualChangePointOption).exec()
            // manualChangePointList.forEach(e=>{
            //     manualChangePoint = manualChangePoint + e.amount
            // })
            res.ok('查询成功', data)
        } catch (e) {
            next(e)
        }
    },

};